#ifndef CODEEDITOR_H
#define CODEEDITOR_H

#include "highlighter.h"

//基于QPlainTextEdit的CodeEditor文字编辑控件类
class CodeEditor : public QPlainTextEdit
{
public:
    CodeEditor(QWidget *parent = nullptr);

    void lineNumberAreaPaintEvent(QPaintEvent *event);
    int lineNumberAreaWidth();
    bool changeIndent(QString);
    void setComment();
    void changeColorTheme();
    void setShowErrorLine(bool show);
    int getTabSpaceNumber();
    void setTabSpaceNumber(int newNumber);

protected:
    void resizeEvent(QResizeEvent *event) override;
    void wheelEvent(QWheelEvent *e) override;

private:
    QWidget *lineNumberArea=nullptr;
    Highlighter *highlighter = nullptr;
    QStack<QChar> bracketStack;
    int tabSpaceNumber;
    bool showErrorLine;

    void updateLineNumberAreaWidth(int newBlockCount);
    void highlightCurrentLine();
    void updateLineNumberArea(const QRect &rect, int dy);
    void keyPressEvent(QKeyEvent *event) override;	//按键按下事件处理函数
    bool returnPressedAndIndent();
    bool isOperatorFormat(QTextCursor textCursor);
    bool searchPairBrackets(QList<QTextEdit::ExtraSelection>& extraSelections, int offset);
};

//代码编辑控件左边的行数显示控件
class LineNumberArea : public QWidget
{
public:
    LineNumberArea(CodeEditor *editor) : QWidget(editor)
    {
        codeEditor = editor;
    }

    QSize sizeHint() const override
    {
        return QSize(codeEditor->lineNumberAreaWidth(), 0);
    }

protected:
    void paintEvent(QPaintEvent *event) override
    {
        codeEditor->lineNumberAreaPaintEvent(event);
    }

private:
    CodeEditor *codeEditor;
};

#endif
